#include "connectionthread.h"

ConnectionThread::ConnectionThread(int ID ,QObject *parent) :
    QThread(parent)
{
    this->Descriptor = ID;
}

void ConnectionThread::run()
{
    qDebug() << this->Descriptor << ": [*]Start watku";
    socket = new QTcpSocket();
    if (!socket->setSocketDescriptor(this->Descriptor))
    {
        emit error(socket->error());
        return;
    }
    connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::DirectConnection);
    connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()), Qt::DirectConnection);
    qDebug() << this->Descriptor << ": [*]Polaczenie z klientem";

    exec();
}

void ConnectionThread::readyRead()
{
    QByteArray data = socket->readAll();
    qDebug() << this->Descriptor << ": [*]Otrzymano dane: " << data;
//    relayData(data);
}

void ConnectionThread::disconnected()
{
    socket->deleteLater();
    exit(0);
}

void ConnectionThread::writeToSocket(QByteArray data)
{
    qDebug() << socket->isOpen();
    //QByteArray tmp = data;
    //qDebug() << this->socket->isWritable();
    /*this->socket->write(data);
    if (!socket->waitForBytesWritten(5000))
    {
        qDebug() << this->Descriptor << ": [!] ERROR! " << socket->errorString();
    }
    */
}

void ConnectionThread::relayData(QByteArray data)
{
    emit relay(data);
}
